package com.tuanzi.loan.web.bean.system;

import com.tuanzi.loan.business.entity.system.Partner;
import com.tuanzi.loan.business.service.system.PartnerService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.system.PartnerSearchRequest;
import com.tuanzi.loan.vo.response.system.PartnerSearchResponse;
import com.tuanzi.loan.web.configuration.JSFListingSessionBean;
import com.tuanzi.loan.web.lazy.system.PartnerLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.faces.bean.ViewScoped;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Ray 2017/09/21
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class PartnerListBean extends JSFListingSessionBean<PartnerSearchRequest, PartnerSearchResponse> {

    private static final long serialVersionUID = -2152778554108785342L;

    @Autowired
    private PartnerService partnerService;

    public void onReset() {
        initLazyDataModel();
    }

    public void onDisable(String id) {
        Partner partner = partnerService.findOne(id);
        partnerService.disable(partner);
        addSuccessfullyMessage();
    }

    public void onEnable(String id) {
        Partner partner = partnerService.findOne(id);
        partnerService.enable(partner);
        addSuccessfullyMessage();
    }

    public void onBatchDisable() {
        partnerService.disable(getSelectedPartners());
        addSuccessfullyMessage();
    }

    public void onBatchEnable() {
        partnerService.enable(getSelectedPartners());
        addSuccessfullyMessage();
    }

    private List<Partner> getSelectedPartners() {
        return partnerService
                .findAll(selectedRecords.parallelStream().map(PartnerSearchResponse::getId)
                        .map(x -> x.toString()).collect(Collectors.toList()));
    }

    public String onAdd() {
        return redirect("/views/system/partner/partner-info.xhtml");
    }

    public String onEdit(String id) {
        return redirect("/views/system/partner/partner-info.xhtml?id=" + id);
    }

    @Override
    protected String page() {
        return "/views/system/partner/partner-list.xhtml";
    }

    @Override
    protected void initLazyDataModel() {
        $ = new PartnerSearchRequest();
        lazyDataModel = new PartnerLazyDataModel($, session, partnerService);
    }
}
